package com.wp.service;

import com.wp.dao.GoodsDao;
import com.wp.entity.Goods;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author: WangPeng
 * @createTime: 2022/12/08 11:14
 * @description:
 * @version: v1.0
 */
@Service
public class GoodsStockService03_redis {

    @Autowired
    private GoodsDao goodsDao;

    @Autowired
    private StringRedisTemplate redisTemplate;

    public String decrement(Integer id){
        ValueOperations<String, String> forValue = redisTemplate.opsForValue();
        //获取锁对象: 如果返回true表示获取锁成功,如果返回false 获取锁失败
        Boolean flag = forValue.setIfAbsent("goods::" + id, "wp", 120, TimeUnit.MINUTES);
        if (flag){
            try {
                //1. 查找指定商品的库存
                Goods goods = goodsDao.selectById(id);
                //2. 判断库存数是否大于0
                if (goods.getNumber()>0){
                    //3.减库存
                    goods.setNumber(goods.getNumber()-1);
                    int i = goodsDao.updateById(goods);
                    System.out.println("商品编号为:" + id + "的商品库存剩余:" + goods.getNumber() + "个");
                    return "商品编号为:" + id + "的商品库存剩余:" + goods.getNumber() + "个";
                }else {
                    System.out.println("商品编号为:" + id + "的商品库存不足。");
                    return "商品编号为:" + id + "的商品库存不足。";
                }
            }finally {
                //无论是否有异常都要释放锁资源
                redisTemplate.delete("goods::"+id);
            }
        }else {
            //如果获取线程锁失败执行的业务代码，
            System.out.println("服务器正忙,请稍后再试.....");
            return "服务器正忙,请稍后再试.....";
        }
    }
}
